﻿using System;
using System.Collections.Generic;
using System.Windows;

using Microsoft.SharePoint.Client;

using SBPweb.RIA.Client.Contracts.Base;

namespace SBPweb.Sharepoint.Client.Library.Lists
{

    public class ListItemValues : DependencyObjectBase
    {

        protected ListItem item;
        //private bool isInQuery;
        private IDictionary<string, DependencyProperty> dictProperties;

        public ListItemValues()
        {
        }

        internal void SetListItem(IDictionary<string, DependencyProperty> properties, ListItem item)
        {
            this.item = item;
            this.dictProperties = properties;
            foreach (var kvp in properties)
            {
                try
                {
                    SetTypedValue(kvp.Value, item[kvp.Key], kvp.Key);
                }
                catch
                {
                }
            }
        }

        protected object GetValue(string fieldName)
        {
            if (!dictProperties.ContainsKey(fieldName))
            {
                return null;
            }
            return GetValue(dictProperties[fieldName]);
        }

        protected void SetValue(string fieldName, object value)
        {
            if (!dictProperties.ContainsKey(fieldName))
            {
                return;
            }
            SetTypedValue(dictProperties[fieldName], value, fieldName);
        }

        //private void doQuery()
        //{
        //    if (isInQuery)
        //    {
        //        return;
        //    }
        //    isInQuery = true;
        //    item.Context.Load(item);
        //    item.Context.ExecuteQueryAsync(onQuerySucceeded, onQueryFailed);
        //}

        //private void onQuerySucceeded(object sender, ClientRequestSucceededEventArgs args)
        //{
        //    this.Dispatcher.BeginInvoke(() =>
        //    {
        //        foreach (var fN in requestedFields)
        //        {
        //            try
        //            {
        //                SetValue(fN, item[fN]);
        //            }
        //            catch
        //            {
        //            }
        //            //SetTypedValue(kvp.Value, item[kvp.Key], kvp.Key);
        //        }
        //    });
        //    isInQuery = false;
        //}

        //private void onQueryFailed(object sender, ClientRequestFailedEventArgs args)
        //{
        //    isInQuery = false;
        //}

    }

}